package com.example.fw.base;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.example.fw.Application;
import com.myjar.Stringutil;
import com.myjar.desutil.RunException;

@Configuration
public class MyHandlerInterceptor implements HandlerInterceptor {
	
	
	/**
     * 进入controller层之前拦截请求
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	Application.out(
				"=======================================测试开始==================================================");
		String phone = null;
		String k;
		String v;
		Enumeration<String> es = request.getParameterNames();
		Application.out("参数列表");
		StringBuilder sb = new StringBuilder();
		//把参数循环迭代一遍，过滤掉异常的参数
		while (es.hasMoreElements()) {
			k = es.nextElement();
			v = request.getParameter(k);
			sb.append(k).append("=").append(v).append(";");
			Application.out(k+"="+v+",");
			
			if ("uname".equals(k))
				phone = v;
			if (v.contains("'")){
				//这个异常继承自runtimeException，不寻找c语言堆栈信息，效率比系统提供的runtimeException快了十倍
					throw new RunException("参数包含保留字(')");
				
			}
		}
		//测试的时候把用户放到sessio里面，这样添加了参数以后就默认登录
		if(!request.getRequestURI().contains("/user/save")){//添加新用户不做效验
			try {
				if(!Stringutil.isBlank(phone)){
					HttpSession mHttpSession = request.getSession();
//					mHttpSession.setAttribute("user", mJiabiService.getUser(phone));
				}
			} catch (Exception e) {
				throw new RunException("用户:"+phone+"不存在");
			}

		}


        return true;
    }
 
 
    // --------------处理请求完成后视图渲染之前的处理操作---------------
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    	Application.out("处理请求完成后视图渲染之前的处理操作");
    }
 
    // ---------------视图渲染之后的操作-------------------------0
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    	Application.out("视图渲染之后的操作");
    }


}
